package com.jk.stage.utils;

import java.io.IOException;
import java.net.URI;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.alibaba.fastjson.JSONObject;

/**
 * @Author: 王炳智
 * @Description:
 * @Date: 2021/11/21 21:15
 * 短信验证
 * @Return:
 **/
public class HttpClientUtil {
    static CloseableHttpClient client = null;
    static {
        //1、创建httpClient实例
        client = HttpClients.createDefault();
    }
    /**
     * <pre>sendCode(获取短信验证码)
     * 创建人：段梓旺
     * 创建时间：2021年10月20日 上午9:26:11
     * 修改人：段梓旺
     * 修改时间：2021年10月20日 上午9:26:11
     * 修改备注：
     * @param phone 手机号
     * @param appkey key钥匙
     * @param appkey 秘钥
     * @param templateid 短信模板id
     * @return</pre>
     */
    public static JSONObject sendCode(String phone,String appkey,String appSecret,int templateid){
        // 短信验证的 url
        String url = "https://api.netease.im/sms/sendcode.action";

        //设置 Headers 参数
        // 获取6 位随机数
        long nonce = Math.round(Math.random()*899999+100000);
        // 当前时间的时间戳 秒值
        long curtime = System.currentTimeMillis()/1000;
        //开发者 平台分布的 key  appkey
        //String appkey = "22f5c4a7b06afed78a3ac61235bdbefd";
        //秘钥
        // String appSecret="7e0d07e4fb1a";
        // SHA1(AppSecret + Nonce + CurTime)，三个参数拼接的字符串，进行SHA1哈希计算，转化成16进制字符(String，小写)
        String checkSum = HttpClientUtil.getCheckSum(appSecret, nonce+"", curtime+"");
        //存放 Headers 参数
        HashMap<String, Object> header = new HashMap<String, Object>();
        header.put("AppKey", appkey);//开发者平台分配的appkey
        header.put("Nonce", nonce);//随机数
        header.put("CurTime", curtime);//当前UTC时间戳，从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
        header.put("CheckSum", checkSum);//SHA1(AppSecret + Nonce + CurTime)，三个参数拼接的字符串，进行SHA1哈希计算，转化成16进制字符(String，小写)
        // 存放 http 请求参数
        //必有 mobile 手机号
        //templateid 可有可无
        // authCode  验证码 可有可无
        //模板id
        //int templateid=19504903
        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("mobile", phone);//手机号
        params.put("templateid", templateid);//模板id
        params.put("authCode", nonce);//发送的验证码
        // 调用 短信验证的 post 方式
        String str = HttpClientUtil.postSms(url, params, header);
        //处理返回值
        JSONObject returnObj = JSONObject.parseObject(str);
        int code = returnObj.getIntValue("code");
        returnObj.put("nonce", nonce);//验证码
        System.out.println("状态码："+code);
        System.out.println("发送的验证码："+nonce);
        return returnObj;
    }

    //发送短信验证码：给header传参
    public static String postSms(String url,HashMap<String, Object> params,HashMap<String, Object> HeaderParams) {
        try {
            //创建post请求对象
            HttpPost httpPost = new HttpPost();
            //设置路径
            httpPost.setURI(new URI(url));

            //设置请求的header
            Set<String> headerKey = HeaderParams.keySet();
            for (String key : headerKey) {
                httpPost.addHeader(key, HeaderParams.get(key).toString());
            }

            //设置post请求参数
            //a、hashmap的遍历：获取里面的key和value
            //b、拼接list
            List<NameValuePair> parameters = new ArrayList<NameValuePair>();
            Set<String> keySet = params.keySet();
            for (String key : keySet) {
                NameValuePair e = new BasicNameValuePair(key, params.get(key).toString());
                parameters.add(e);
            }

            HttpEntity entity = new UrlEncodedFormEntity(parameters , "utf-8");
            httpPost.setEntity(entity);

            //执行：发送请求
            CloseableHttpResponse execute = client.execute(httpPost);
            //获取请求的状态码
            int statusCode = execute.getStatusLine().getStatusCode();
            if (200 != statusCode) {
                return "";
            }
            return EntityUtils.toString(execute.getEntity(), "utf-8");
        }catch (Exception e) {
            //6、关闭连接
            try {
                client.close();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            e.printStackTrace();
            return null;
        }
    }

    // 计算并获取CheckSum
    public static String getCheckSum(String appSecret, String nonce, String curTime) {
        return encode("sha1", appSecret + nonce + curTime);
    }

    // 计算并获取md5值
    public static String getMD5(String requestBody) {
        return encode("md5", requestBody);
    }

    private static String encode(String algorithm, String value) {
        if (value == null) {
            return null;
        }
        try {
            MessageDigest messageDigest
                    = MessageDigest.getInstance(algorithm);
            messageDigest.update(value.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }
    private static final char[] HEX_DIGITS = { '0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
}
